package com.blb.java12springsecutiry.config;

import com.blb.java12springsecutiry.entity.vo.UserTokenVO;
import com.blb.java12springsecutiry.util.JwtUtils;
import com.blb.java12springsecutiry.util.ResponseResult;
import com.blb.java12springsecutiry.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lvtian
 * @date 2023/2/1 16:16
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    //登陆成功的回调
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得用户名
        User user = (User) authentication.getPrincipal();
        //生成token
        String token = JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey,JwtUtils.EXPIRE_MINUTES);
        log.info("生成token：{}", token);
        //发送token给前端
        ResponseResult.write(httpServletResponse,ResponseResult.ok(new UserTokenVO(user.getUsername(), token)));

    }
}
